﻿import 'dart:async';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:audioplayers/audioplayers.dart';
import 'audio_player_state.dart';
import '../../../core/models/action_record.dart';

/// 音频播放控制器
class AudioPlayerLogic extends GetxController {
  /// 状态实例
  final AudioPlayerState state = AudioPlayerState();
  
  /// 音频播放器
  late AudioPlayer _audioPlayer;
  
  /// 课程信息
  ActionRecord? course;

  @override
  void onInit() {
    super.onInit();
    // 获取传递的课程信息
    course = Get.arguments as ActionRecord?;
    _initializeAudio();
  }

  @override
  void onClose() {
    _audioPlayer.dispose();
    super.onClose();
  }

  /// 初始化音频
  void _initializeAudio() {
    _audioPlayer = AudioPlayer();
    
    // 监听播放状态
    _audioPlayer.onPlayerStateChanged.listen((PlayerState playerState) {
      state.isPlaying.value = playerState == PlayerState.playing;
    });
    
    // 监听播放进度
    _audioPlayer.onPositionChanged.listen((Duration position) {
      state.currentPosition.value = position.inSeconds.toDouble();
    });
    
    // 监听总时长
    _audioPlayer.onDurationChanged.listen((Duration duration) {
      state.totalDuration.value = duration.inSeconds.toDouble();
    });
    
    // 监听播放完成
    _audioPlayer.onPlayerComplete.listen((event) {
      _onPlaybackComplete();
    });
    
    // 加载音频文件并自动播放
    if (course != null && course!.fullFileUrl.isNotEmpty) {
      _loadAudio();
    }
  }

  /// 加载音频文件
  Future<void> _loadAudio() async {
    try {
      await _audioPlayer.setSourceUrl(course!.fullFileUrl);
      // 自动开始播放
      await play();
    } catch (e) {
      print('加载音频失败: $e');
      Toast.show('加载音频失败');
    }
  }

  /// 播放音频
  Future<void> play() async {
    try {
      await _audioPlayer.resume();
    } catch (e) {
      print('播放失败: $e');
    }
  }

  /// 暂停音频
  Future<void> pause() async {
    try {
      await _audioPlayer.pause();
    } catch (e) {
      print('暂停失败: $e');
    }
  }

  /// 快退15秒
  Future<void> rewind() async {
    final newPosition = (state.currentPosition.value - 15).clamp(0.0, state.totalDuration.value);
    await seekTo(newPosition);
  }

  /// 快进15秒
  Future<void> fastForward() async {
    final newPosition = (state.currentPosition.value + 15).clamp(0.0, state.totalDuration.value);
    await seekTo(newPosition);
  }

  /// 跳转到指定位置
  Future<void> seekTo(double position) async {
    try {
      await _audioPlayer.seek(Duration(seconds: position.toInt()));
    } catch (e) {
      print('跳转失败: $e');
    }
  }

  /// 播放完成
  void _onPlaybackComplete() {
    state.isPlaying.value = false;
    state.currentPosition.value = 0;
    
    Toast.show('恭喜！您已完成 ${course?.actionName ?? "课程"} 的学习');
    
    // 2秒后返回
    Future.delayed(const Duration(seconds: 2), () {
      Get.back();
    });
  }

  /// 格式化时长显示
  String formatDuration(double seconds) {
    final int hours = (seconds / 3600).floor();
    final int minutes = ((seconds % 3600) / 60).floor();
    final int remainingSeconds = (seconds % 60).floor();
    
    if (hours > 0) {
      return '${hours.toString().padLeft(1, '0')}:${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
    }
    return '${minutes.toString().padLeft(1, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }
}
